<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// "Hackware Web Services Core" is released under the MIT License terms.

namespace Hawese\Core\Providers;

use Illuminate\Support\ServiceProvider;

class CoreServiceProvider extends ServiceProvider
{
    const BASEDIR = __DIR__ . '/../..';

    public function register()
    {
        // Service container bindings

        // The following define which implementation of a Contract to use
        $this->app->singleton(
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
            \Hawese\Core\Exceptions\Handler::class
        );
        $this->app->singleton(
            \Illuminate\Contracts\Console\Kernel::class,
            \Laravel\Lumen\Console\Kernel::class
            // \Hawese\Core\Console\Kernel::class // Probably in future
        );

        // Service providers setup package resources such as database
        // migrations, environment configuration setup and routes (this
        // is a service provider, duh!).

        // Required service providers
        $service_providers = [
            \Hawese\Core\Providers\SessionServiceProvider::class,
            \Hawese\Core\Providers\AuthServiceProvider::class,
            \Hawese\Core\Providers\MailerServiceProvider::class,
            \Spatie\Cors\CorsServiceProvider::class,
        ];
        foreach ($service_providers as $service_provider) {
            $this->app->register($service_provider);
        }

        $optional_service_providers = [
            'Hawese\Wallet\Providers\WalletServiceProvider',
            'Hawese\Payment\Providers\PaymentServiceProvider',
            'Laravel\Tinker\TinkerServiceProvider',
        ];
        foreach ($optional_service_providers as $service_provider) {
            if (class_exists($service_provider)) {
                $this->app->register($service_provider);
            }
        }
    }

    public function boot()
    {
        $this->loadRoutesFrom(self::BASEDIR . '/routes/core.php');
        $this->loadMigrationsFrom(self::BASEDIR . '/database/migrations');
        $this->loadViewsFrom(self::BASEDIR . '/resources/views', 'core');

        // Global middlewares
        $this->app->middleware([
            \Spatie\Cors\Cors::class,
        ]);

        // Register route middleware for avaibility
        $this->app->routeMiddleware([
            'auth' => \Hawese\Core\Http\Middleware\Authenticate::class,
            'throttle' => (
                \Illuminate\Routing\Middleware\ThrottleRequests::class
            ),
        ]);

        // Looks like url generation is inconsistent, I don't like that
        $this->app->url->forceRootUrl(config('app.url'));
    }
}
